<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHader @addList="addList"></TodoHader>

    <!-- 主体部分 -->
    <TodoBody 
    :list="renderList" 
    :listIsdone="listIsdone"
    @delList="delList"
    @changeSalist="changeSalist"
    @checkedAll='checkedAll'
    ></TodoBody>

    <!-- 底部部分 -->
    <TodoFooter 
    :residue="residue"
    :type="type"
    :islListAll="islListAll"
    @cleanup="cleanup"
    @changeType="changeType"
    v-show="list.length"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHader from "./components/TodaHader.vue";
import TodoBody from "./components/TodaBody.vue";
import TodoFooter from "./components/TodaFooter.vue";
import { watch } from 'vue';

export default {
  components: {
    TodoHader,
    TodoBody,
    TodoFooter,
  },
  data() {
    return {
      type:'all',
      list: JSON.parse(localStorage.getItem("list") ) || [
        { id: 1, name: "吃饭", isDone: true },
        { id: 2, name: "睡觉", isDone: false },
        { id: 3, name: "打豆豆", isDone: true },
      ],
    };
  },

  methods:{
    // 删除事件
    delList(id){
      this.list = this.list.filter(item=> item.id !== id)
    },
    // 修改状态事件
    changeSalist(id){
      const arr = this.list.find(item => item.id === id)
      // console.log(arr);
      arr.isDone = !arr.isDone
    },
    // 添加事件
    addList(value){
      // console.log(value);
      // console.log(+new Date());
      const obj = { id: +new Date(), name:value, isDone: false }
      this.list = [obj,...this.list ]
    },

    // 清除已完成的
    cleanup(){
      this.list = this.list.filter(item => !item.isDone)
    },

    // 修改type
    changeType(type){
      this.type = type
    },

    checkedAll(data){
      this.list.forEach(item => item.isDone = data)
    },
  },

  // 计算属性
  computed:{
    // 
    residue(){
      return this.list.filter(item => !item.isDone).length
    },
    // 
    islListAll(){
      return this.list.some(item => item.isDone === true)
    },

    renderList(){
      switch (this.type) {
        case 'all':
          return this.list
          break;
        case 'active':
          return this.list.filter(item => !item.isDone)
          break;
        case 'completed':
          return this.list.filter(item => item.isDone)
          break;
        default:
          return this.list
          break;
      }
    },

    listIsdone(){
      return this.list.every(item => item.isDone)
    }

  },

  // 监视属性
  watch:{
    "list":{
      deep:true,
      handler(){
        localStorage.setItem("list",JSON.stringify(this.list))
      }
    },
  },
};
</script>

<style></style>
